package org.zachary.agent.interfaces;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.zachary.agent.application.*;
import org.zachary.agent.domain.aggregate_model.token.Token;
import org.zachary.agent.domain.aggregate_model.user.User;
import org.zachary.agent.domain.service.FeignService;
import org.zachary.agent.infrastructure.repository.UserIdCountryProjection;
import org.zachary.agent.infrastructure.utils.Result;
import org.zachary.agent.interfaces.commands.*;

import java.util.List;
import java.util.Map;

@Api(tags = "用户模块")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    private final UserRegistrationService registrationService;
    private final UserLoginService loginService;
    private final TokenRefreshService tokenRefreshService;
    private final UserService userService;
    private final FeignTestService feignTestService;


    public UserController(UserRegistrationService registrationService, UserLoginService loginService, TokenRefreshService tokenRefreshService, UserService userService, FeignTestService feignTestService) {
        this.registrationService = registrationService;
        this.loginService = loginService;
        this.tokenRefreshService = tokenRefreshService;
        this.userService = userService;
        this.feignTestService = feignTestService;
    }

    @PostMapping("/register")
    public Result<Integer> register(@RequestBody RegisterCommand dto) throws Exception {
        Integer code=registrationService.register(dto.getUsername(), dto.getPassword());
        if(code==200){
            return Result.success("注册成功",code);
        }
        return Result.fail("注册失败,用户已存在");
    }

    @PostMapping("/county")
    public Result<Map<Integer,UserIdCountryProjection>> loadCountyById(@RequestBody IdsWrapper wrapper){
        try{
            List<Integer> ids = wrapper.getIds();
            System.out.println(ids);
            Map<Integer, UserIdCountryProjection> byIds = userService.findCountyByIds(ids);
            return Result.success(byIds);
        }catch (Exception e){
            log.error(e.getMessage());
            return Result.fail("数据加载失败");
        }
    }

    @PostMapping("update")
    public Result<String> improveUserInfo(@RequestParam("uuid") String uuid,@RequestBody UpdateCommand dto) throws Exception {

        User user=User.create(dto.getUsername(),dto.getNickname(),
                dto.getProfilePicture(),
                dto.getEmail(),dto.getPhone(),
                dto.getGender(),dto.getProvince(),
                dto.getCity(),dto.getCountry(),
                dto.getTownship());
        userService.updateUserInfo(uuid,user);
        return Result.success();
    }

    @PostMapping("/login")
    public Result<Token> login(@RequestBody LoginCommand dto) throws Exception {
        Token token = loginService.login(
                dto.getUsername(),
                dto.getPassword(),
                dto.getDevice()
        );

        log.info("device="+dto.getDevice());
        return Result.success(token);
    }
    @PostMapping("/admin/login")
    public Result<Token> AdminLogin(@RequestBody LoginCommand dto) throws Exception {
        Token token = loginService.login(
                dto.getUsername(),
                dto.getPassword(),
                dto.getDevice()
        );

        log.info("device="+dto.getDevice());
        return Result.success(token);
    }
    @GetMapping("/logout")
    public Result<String> logout(@RequestParam("userId") String userId,@RequestParam("device") String deviceId){
        loginService.logout(userId,deviceId);
        System.out.println("用户退出登录");
        return Result.success("用户已登出");
    }

    @GetMapping("/info")
    public Result<User> getUserInfo(@RequestParam("userId") String userId) throws Exception {
        User user=userService.getUserInfo(userId);
        if(user.getNickName()==null||user.getProfilePicture()==null||
                user.getPhone()==null || user.getEmail()==null||
                user.getTownship()==null){
            System.out.println("用户信息为完善");
            return Result.fail("请完善用户信息");
        }
        System.out.println(user);
        return Result.success(user);
    }


    @GetMapping("/get")
    public Result<String> testFeign(){
        return Result.success(feignTestService.sayHello());
    }



    @PostMapping("/refresh")
    public Result<Token> refreshToken(@RequestBody RefreshTokenCommand dto) throws Exception {
        System.out.println(dto);
        Token token = tokenRefreshService.refresh(
                dto.getAccessToken(),
                dto.getRefreshToken(),
                dto.getUserId(),
                dto.getDevice()
        );
        return Result.success(token);
    }

    @GetMapping("/validator")
    public Result<String> validatorLoginStatus(){
        return Result.success();
    }
    @GetMapping("/avatar/update")
    public Result<String> updateAvatar(@RequestParam("userId") Integer userId,@RequestParam("url")String url) throws Exception {
        userService.updateUserAvatar(userId,url);
        return Result.success("更新成功");
    }
}
